 import axios from 'axios'
 import { ref } from 'vue'
 import { showFailToast } from 'vant'
 import { setLocal } from '@/common/js/utils'
 import router from '../router'

const localTenantId = localStorage.getItem('TENANTID') || ''
const localToken = localStorage.getItem('TOKEN') || ''

 const authInfo = ref({
    tenantId: localTenantId,
    accessToken: localToken
 });

 export const useAuthInfoHook = () => {
     return authInfo;
 };

 axios.defaults.baseURL = '/'
 axios.defaults.withCredentials = true
 axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
 axios.defaults.headers.post['Content-Type'] = 'application/json'

 axios.interceptors.request.use(config => {
     if (authInfo.value.tenantId) {
         config.headers["tenant-id"] = authInfo.value.tenantId;
     }
     if (authInfo.value.accessToken) {
         config.headers["Authorization"] =
             `Bearer ${authInfo.value.accessToken}`;
     }
     return config;
 },)

 axios.interceptors.response.use(res => {
   if (typeof res.data !== 'object') {
    showFailToast('服务端异常！')
     return Promise.reject(res)
   }
   if (res.data.code != 0) {
     if (res.data.message) showFailToast(res.data.message)
     if (res.data.code == 410) {
       router.push({ path: '/login' })
     }
     if (res.data.data && window.location.hash == '#/login') {
       setLocal('token', res.data.data)
       axios.defaults.headers['token'] = res.data.data
     }
     return Promise.reject(res.data)
   }

   return res.data
 })
 const objectToUrlParams = (obj: {[key:string]: string | number}) => {
  // 将对象转换为键值对数组
  const paramsArray: string[] = [];
  for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
          paramsArray.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
      }
  }
  // 将数组用 '&' 符号连接成字符串
  return paramsArray.join('&');
}
 
 class Request {
  get(url: string, params: {[key:string]: string | number}| undefined = undefined, config:any = undefined) {
    if(params) url = url + '?' + objectToUrlParams(params)
    return axios.get(url, config)
  }
  post(url: string, data: any, config:any = undefined) {
    return axios.post(url, data, config)
  }
 }
 const http = new Request()
 export default http
 